package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.quest.QueryObject;
import cn.wolfcode.result.PageResult;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void deleteByPrimaryKey(Long id) {
        roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void insert(Role record) {
        roleMapper.insert(record);
    }

    @Override
    public Role get(Long id) {
        Role role = roleMapper.selectByPrimaryKey(id);
        return role;
    }
    @Override
    public List<Role> selectAll() {
        List<Role> roles = roleMapper.selectAll();
        return roles;
    }
    @Override
    public void updateByPrimaryKey(Role record) {
        roleMapper.updateByPrimaryKey(record);
    }

    @Override
    public PageInfo<Role> query(QueryObject qo) {
        //根据条件查询出总数量
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
       /* int i = roleMapper.selectForCount(qo);
        if (i==0){
            return new PageResult<Role>(qo.getCurrentPage(),qo.getPageSize(),0, Collections.emptyList());
        }
        //如果数量不为0*/
        List<Role> roles = roleMapper.selectForList(qo);
       /* if (roles.size()<=0&&qo.getCurrentPage()>1){
            qo.setCurrentPage(qo.getCurrentPage()-1);
            roles = roleMapper.selectForList(qo);
        }*/

      /*  PageResult<Role> result = new PageResult<>(qo.getCurrentPage(), qo.getPageSize(), i, roles);
*/
        return new PageInfo<>(roles);
    }

    @Override
    public void insertPer(Role role, Long[] ids) {
        //先添加角色数据
        roleMapper.insert(role);
        //调用方法,直接添加关系表数据
        if (ids!=null){
            roleMapper.insertPremission(role, ids);
        }
    }

    @Override
    public void updatePer(Role role, Long[] ids) {
        //先更新角色表的数据
        roleMapper.updateByPrimaryKey(role);
        //删除关系表中原有的数据
        roleMapper.deletePremission(role);
        //添加关系表数据
        if (ids!=null){
            roleMapper.insertPremission(role, ids);
        }
    }
}
